package org.zxy.org.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.zxy.org.domain.Department;
import org.zxy.org.domain.Employee;
import org.zxy.org.mapper.DepartmentMapper;
import org.zxy.org.mapper.EmployeeMapper;
import org.zxy.org.service.IEmployeeService;
import org.zxy.base.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author rain
 * @since 2024-04-16
 */
@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public Employee queryByUsername(String username) {
        return employeeMapper.queryByUsername(username);
    }

    @Override
    @Transactional
    public void importExcel(List<Employee> employeeList) {
        for (Employee employee : employeeList) {
            if (employee.getDepartment().getName() != null) {
                Department department = departmentMapper.selectByName(employee.getDepartment().getName());
                employee.setDepartment(department);
            }
        }
        employeeMapper.fileInsert(employeeList);
    }

    @Override
    public void exportExcel(String key) {
        List<Employee> employees = employeeMapper.selectByKey(key);
        for (Employee employee : employees) {
            Department department = departmentMapper.selectByName(employee.getDepartment().getName());
            employee.setDepartment(department);
        }
        try {
            ExportParams exportParams = new ExportParams();
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Employee.class, employees);
            //导出的地址
            FileOutputStream os = new FileOutputStream("C:\\Users\\赵鑫宇\\Desktop\\employee.xlxs");
            workbook.write(os);
            os.close();
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
